<template>
	<view class="home">
        <view class="login-alert" v-show="alertText">
            <text>{{alertText}}</text>
        </view>
		<!-- <uni-popup ref='popup' type="center" class="popup_default" :maskClick='isClosePop' >
			<uni-popupDefault
				:isExit="isExit"
				:popup="popupData"
				:isShowTitle="isShowTitle"
				:isShowContent="isShowContent"
				:isShowImg="isShowImg"
				@exit='exit'
				>
			</uni-popupDefault>
		</uni-popup> -->
        <view class="form">
        	<view class="form-title">账号</view>
        	<input class="uni-input" name="username" maxlength="30" v-model="username" placeholder="请输入账号" />
            <view class="form-action"></view>
        </view>
        <view class="form">
        	<view class="form-title">密码</view>
        	<input class="uni-input" name="password" type="password" maxlength="30" v-model="password" placeholder="请输入密码" />
            <view class="form-action"></view>
        </view>
        <view class="form top-margin">
        	<view class="form-title">所属棋协</view>
            <picker class="picker" mode="selector"  :range="orgList" range-key="org_name" :value="orgIndex" @change="orgChange">
                <input class="uni-input" name="orgname" disabled="true" :value="selectedOrg" placeholder="选择所属棋协" />
                <uni-icons class="picker-icons" type="arrowright"  size="20" />
            </picker>
        </view>
        <button @click="loginFun"  class="btn">登录</button>
		<!-- 选择棋协 -->
			<!-- <uni-chessselect
				:pickArray="array_chess"
				@selected="toSelectChess"
				v-if="isPicker"
				>
				</uni-chessselect> -->

	</view>
</template>
<script>
	import uniPopupDefault from "@/components/uni-event/uni-popupdefault.vue";
	import	uniChessselect from "@/components/uni-event/uni-chessselect.vue";
	import uniPopup  from "@/components/uni-popup/uni-popup.vue";
	import { setCookie, getCookie, md5 } from "@/common/util.js";
	import { authorizedList,chessAccount_hfive,receiveToken_hfive,chessAccount,receiveToken, getMsOrg } from "@/common/api.js";
	export default{
		data(){
			return{
				isExit:true,  //是否退出小程序
				popupData:{},
				isShowContent:true,
				isClosePop:true,  //点击遮罩层，是否关闭弹出框
				isShowImg:true,  //显式二维码
				isShowTitle:false,  //显式标题
				isCloseSelect:true,
				array_chess:[],   //所有棋协
				select_chess:{}, //选择的棋协
				isPicker:false,
				accountnum:"",
				alertText:''  ,//提示语
				code:"",
				username:'',
				password:'',
				orgList:[],
				selectedOrg:'',
				orgIndex:'',
				selectedUnder:'',
				selectedOrgValue:'',
                openid:''
			}
		},
		components:{
			uniPopupDefault,
			uniPopup,
			uniChessselect
		},
		onShow() {
			var _this=this;
			// uni.showLoading({
			// 	title:"加载中..."
			// })
			// setTimeout(function () {
			// 	//#ifdef H5
			// 	_this.getOrg();
			// 	//#endif

			// 	//小程序
			// 	//#ifdef MP-WEIXIN
				// _this.getRuntineOrg()
			// 	//#endif
				_this.getOrgList()
			// 	uni.hideLoading();
			// }, 1000);
		},
		methods:{
			toSelectChess(e){
				var _this=this;
				_this.select_chess=_this.array_chess.filter(function(item,index){
					return e==index
				})[0];
				//#ifdef H5
					_this.getToken();
				//#endif

				//小程序
				//#ifdef MP-WEIXIN
					_this.getRuntineToken()
				//#endif
			},
			exit(){
				var _this=this;
				_this.$refs.popup.close()
			},
			//小程序登录
			getRuntineOrg(){
				var _this=this;
				uni.login({
					provider:"weixin",
					success(data) {
					_this.code=data.code;
					}
				})
			},
			//h5
			// getOrg(){
			// 	var _this=this,openID="owUDMsxX4rQZr3rKsgtp5LOmcGpQ";
			// 	var tokens="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6IjRmMWcyM2ExYXNkIn0.eyJpc3MiOiJodHRwOlwvXC93d3cueXVuYmlzYWkuY29tIiwiYXVkIjoibHN3bF9zbmFrZSIsImp0aSI6IjRmMWcyM2ExYXNkIiwiaWF0IjoxNTc2MDU0Mjk1LCJuYmYiOjE1NzYwNTQyOTUsImV4cCI6MTU3NjA2ODY5NSwiaW5mbyI6eyJ1c2VySUQiOiI3IiwibHN3bF9vcmdfaWQiOiI3ODAiLCJ1c2VyTmFtZSI6Ilx1NTkyOVx1NTgwMlx1OGY2Zlx1NGVmNlx1NTZlZCIsImlzX2FkbWluIjoiMSIsInVuZGVyIjoiMzMiLCJvcmdJRCI6IjYiLCJwYXJlbnRfaWQiOiIxIiwib3JnTmFtZSI6Ilx1NTkyOVx1NTgwMlx1OGY2Zlx1NGVmNlx1NTZlZCIsIm9yZ0xldmVsIjoiMiIsInNlc3Npb25faWQiOiJ1MWo3MXU4N2s0ZjUzMzNvbDVpdGM0aGhrMSIsImxvZ2luSUQiOiI3NjkzIiwiaXNfcGVyc29uIjowLCJvcmdfZ3JvdXAiOiIwIiwib3JnX3N0YXRlIjoiMiJ9fQ.vNrceHs6n-m8Z8aJKmHlRRViWkUlvP93-MIYWbWg658"
			// 	if(uni.getStorageSync('token')){
			// 		var data={
			// 			type: "wait",
			// 			page: 1,
			// 			pageSize: 20,
			// 		}
			// 		authorizedList(data).then(function(res){
			// 			var e=res.data;
			// 			if(e.errcode==1000||e.errcode==1001){
			// 				window.location.href="//m.yunbisai.com/wechat/Oauth/index";
			// 			}else{
			// 				uni.navigateTo({
			// 					url:'/pages/home/index'
			// 				})
			// 			}
			// 		})
			// 	}else{
			// 			// window.location.href="//m.yunbisai.com/wechat/Oauth/index";
			// 		_this.getChess()
			// 	}
			// },
			getRuntineToken(){
				var _this=this,under=Number(_this.select_chess.under);
				var data={
					under:under,
					code:_this.code
				}
				receiveToken(data).then(function(res){
					var e=res.data;
					console.log(res)
					if(e.error==0){
						if(e.datArr&&e.datArr!=null){
							_this.select_chess['level']=e.level;
							_this.select_chess['org_id']=e.org_id;
							_this.select_chess['accountnum']=_this.accountnum;
							_this.select_chess["openid"]=_this.openid;
							uni.setStorageSync('account',_this.select_chess)
							uni.setStorageSync('token',e.datArr);
							uni.navigateTo({
								url:'/pages/home/index'
							})
						}
					}else{
						 _this.alertText=e.msg || '网络错误，请咨询浙江龙蛇网络科技有限公司在线客服（微信号：yunbisai）或致电客服热线：0571-85220313。'
					}
				})
			},
			getChess(){
				var _this=this,openID="owUDMsxX4rQZr3rKsgtp5LOmcGpQ";
				setCookie("openid",openID)
				if(getCookie('openid')){
					uni.setStorageSync("openid",getCookie('openid'))
					var data={
						openid:getCookie('openid')
					}
					chessAccount_hfive(data).then(function(res){
						var e=resta;
						_this.accountnum=e.datArr.length;
						if(e.datArr.length==1){
							_this.select_chess=e.datArr[0];
							_this.getToken()
						}else{
							_this.array_chess=e.datArr;
							_this.isPicker=true;
						}
					})
				}
			},
			getToken(){
				var _this=this,under=Number(_this.select_chess.under),data={under:under,openid:uni.getStorageSync('openid')};
				receiveToken_hfive(data).then(function(res){
					var e=resta;
					if(e.datArr&&e.datArr!=null){
						var account={
							accountnum:_this.accountnum,
							level:e.level,
							openid:e.result.openid
						}
						uni.setStorageSync('account',account)
						uni.setStorageSync('token',e.datArr);
						uni.navigateTo({
							url:'/pages/home/index'
						})
						}
				}).catch(function(e){
					uni.showToast({
						position: 'center',
						icon: 'none',
						title:e.msg
					});
				})
			},
            orgChange(e){
                // console.log(e);
                this.selectedOrg=this.orgList[e.detail.value].org_name;
                this.selectedOrgValue = this.orgList[e.detail.value].under;
            },
            loginFun(){
                if(!this.username){
                    uni.showToast({
                        icon: 'none',
                        title: '请输入账号'
                    })
                    return;
                }
                if(!this.password){
                    uni.showToast({
                        icon: 'none',
                        title: '请输入密码'
                    })
                    return;
                }
                if(!this.selectedOrg){
                    uni.showToast({
                        icon: 'none',
                        title: '请选择棋协'
                    })
                    return;
                }
                uni.removeStorageSync('token');
                chessAccount({
                    openid:this.openid,
                    pwd:md5(this.password),
                    name:this.username,
                    under:this.selectedOrgValue
                }).then((res)=>{
                    const data = res.data;
                    if(data.error==0){
                        this.select_chess['level']=data.level;
                        this.select_chess['org_id']=data.org_id;
                        this.select_chess['org_name']=this.username;
                        this.select_chess["openid"]=this.openid;
                        //this.select_chess['accountnum']=_this.accountnum;
                        //this.select_chess["openid"]=_this.openid;
                        uni.setStorageSync('account',this.select_chess)
                        uni.setStorageSync('token',data.datArr);
                        uni.redirectTo({
                            url:'/pages/home/index'
                        })
                        this.username='';
                        this.password='';
                    }else{
                        uni.showToast({
                            icon: 'none',
                            title:data.msg
                        });
                    }
                })
            },
            getOrgList(){
                this.selectedUnder = uni.getStorageSync('_underKey_')
                uni.login({
                	provider:"weixin",
                	success:(data) => {
                        getMsOrg({type:'wx',code:data.code,key:this.selectedUnder}).then((res)=>{
                            const data = res.data;
                            if(data.errcode==0){
                                this.openid = data.result.openid;
                                this.orgList=[...data.list]
                                if(this.orgList.length==1){
                                    this.selectedOrg = this.orgList[0].org_name
                                    this.selectedOrgValue = this.orgList[0].under
                                }
                                if(data.under){
                                    this.selectedOrg = this.orgList.find((e)=>e.under==data.under).org_name
                                    this.selectedOrgValue = data.under
                                }
                            }else{
                                uni.showToast({
                                    icon: 'none',
                                    title:data.msg
                                });
                            }
                        })
                    }
                })
            }
		}
	}
</script>

<style lang="less" scoped>
	.popup_default{
		width: 100%;
	}
	.popup_picker{
		width: 100%;
	}
    .login-alert{
        padding: 15px;
        font-size: 14px;
        margin-top: 20px;
    }
    .top-margin{
        margin-top: 20rpx;
    }
    .home{
        .form{
            display: flex;
            align-items: center;
            flex: 1;
            background: #fff;

            flex-direction: row;
            justify-content: space-between;
            .picker{
                width: 100%;
                margin-left: 40rpx;
                position: relative;
                .picker-icons{
                    bottom: 0px;
                    right: 40rpx;
                    position: absolute;
                }
            }
            .form-title{
                padding: 20rpx;
                padding-left: 30rpx;
                width: 155rpx;
            }
            .form-action{
                padding: 10rpx 30rpx;
                display: flex;
                .sendBtn{
                    color: #000;
                }
            }
        }
        .btn{
            margin: 30rpx;
            font-size: 32rpx;
            margin-top: 60rpx;
            border-radius: 50rpx;
            color: #fff;
            background: #1A66FF;
        }
    }
</style>
